import { getMemberAdd, apiOrderCreate, getPayOrderHelp } from '../../api/index'
let app = getApp()
let page = {
  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    selectpay: false,
    hasAddress: false,
    skuData: {},
    totoalPrice: 0,
    shipping: [],
    goodsDetails: {},
    express_fee: 0
  },
  getDefAdd () {
    getMemberAdd().then(
      res => {
        for (let i = 0; i < res.data.data.length; i++) {
          if (res.data.data[i].is_default === 1) {
            this.setData({
              address: res.data.data[i]
            })
          }
        }
      }
    )
  },
  getHelpInfo (data) {
    getPayOrderHelp({
      goods_id: data.goods_id,
      help_user_id: data.id
    }).then(res => {
      console.log(res.data.express_company_list)
      this.setData({
        goodsDetails: res.data,
        express_fee: res.data.express_company_list.length > 0 ? res.data.express_company_list[0].express_fee.toFixed(2) : '0.00'
      })
    })
  },
  changeAdd (add) {
    if (add) {
      this.setData({
        address: add
      })
      // 切换地址重新请求运费
      this.getHelpInfo(this.helpGoods)
    } else {
      this.getDefAdd()
    }
  },
  // 获取地址
  getAddress () {
    wx.navigateTo({
      url: '../add-admin/add-admin'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    let data = JSON.parse(options.data)
    // 从助力进入
    this.helpInit(data)
    this.help_user_id = data.id
    this.helpGoods = data

    this.setData({
      isIphoneX: app.globalData.isIphoneX,
      skuData: JSON.parse(options.data)
    })
  },
  helpInit (data) {
    this.getHelpInfo(data)
    this.changeAdd()
  },
  // 去支付
  toPayment () {
    if (this.data.address.consigner) {
      let params = {
        goods_sku_list: this.data.goodsDetails.goods_sku_list,
        pay_type: 0,
        shipping_company_id: 0,
        leavemessage: '',
        shipping_type: 1,
        help_user_id: this.help_user_id
      }
      let data = JSON.stringify(this.data.skuData)
      apiOrderCreate(params).then(
        res => {
          wx.redirectTo({
            url: `../payment/payment?out_trade_no=${res.data.out_trade_no}&id=${res.data.order_id}&data=${data}&help_type=1`
          })
        }).catch()
    } else {
      wx.showModal({
        title: '提示',
        content: '请选择收货地址',
        success (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../add-admin/add-admin'
            })
          }
        }
      })
    }
  },
  // 跳转到优惠券
  toCoupon () {
    wx.navigateTo({
      url: '../coupon/coupon'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {

  }
}
Page(page)
